package com.rovinj_server.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.rovinj_server.R;
import com.rovinj_server.adapter.RecyclerAdapter;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.InventorySub;
import com.rovinj_server.holder.RecycleHolder;
import com.rovinj_server.receiver.KeyReceiverListener;
import com.rovinj_server.utisl.CWSoundPoolUtil;
import com.rovinj_server.utisl.Util;
import com.rovinj_server.utisl.UtilNbu;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pda.serialport.Barcode1DManager;


/**
 * 扫描条码
 * 判断是否库位条码
 * 库位条码 查出 库位对应的  条码
 * 扫描到条码 判断是否 扫描到 库位条码 ， 没库位条码 提示
 * 扫描到条码 在对应款号 数量加1
 * 扫描到新条码 在全部单找出对应 款式 增加 集合
 * 存入数据库
 * 扫描到 已经扫描的提示
 * //////////////////////////////////////更改需求
 * <p>
 * 扫描 条码 显示 货位  ，货位对应的信息 数量 显示
 * <p>
 * 再次扫描条码 判断 是否相同货位 ，不相同货位提示， 相同货号 数量增加
 * 提示 可以在这个货位增加  可以取消
 * <p>
 * <p>
 * 我改扫描 条码  显示 对应货位号 ，扫描到其他货位的条码 提示或者数量过多提示，这个功能，  演示给你看看与你们之前的盘点有没好处，或者要改进的地方 在做 后面那个功能
 * <p>
 * ------------------------------------再次更改
 */

public class FragmentInventorySaninng extends Fragment implements KeyReceiverListener {
    public static final String TAG = "-----FragmentInventorySaninng";
    @Bind(R.id.disc_number)
    TextView mDiscNumber;
    @Bind(R.id.sao_sj_qty)
    TextView mSaoSjQty;
    @Bind(R.id.location)
    EditText mLocation;
    @Bind(R.id.butt_saninng)
    Button mButtSaninng;
    @Bind(R.id.but_chongsao)
    Button mButChongsao;
    @Bind(R.id.recycler_view_m)
    RecyclerView mRecyclerViewM;
    @Bind(R.id.ll_butt)
    LinearLayout mLlButt;
    @Bind(R.id.but_submit)
    Button mButSubmit;
    @Bind(R.id.add_qty4)
    TextView mAddQty4;
    @Bind(R.id.add_qty3)
    TextView mAddQty3;
    private Context mContext;
    private View mView;
    //  private SweetAlertDialog dialog;
    private List<InventorySub> mListSubData = new ArrayList<>();
    private List<InventorySub> mDataList = new ArrayList<>();
    private boolean booleanScainng = false;
    private int mId;
    private Barcode1DManager manager;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == Barcode1DManager.Barcode1D) {
                String str = msg.getData().getString("data").toString();
                String data = str.replace("\r\n", "");
                Log.d(TAG, "--条码--" + data + "-----" + data.length());

                if (data.length() == 13) {
                    UtilNbu.play(1, 0);
                } else {
                    Util.play(1, 0);
                }

                if (data != null && data.length() > 0) {

                    barcode_Validation(data);
                } else {
                    Toast.makeText(mContext, "请继续扫描条码", Toast.LENGTH_SHORT).show();
                }

            }
            switch (msg.what) {
                case 0:   // 获取货位
                    if (mDataList != null && mDataList.size() > 0) {
                        mAdapter.setDatas(mDataList);
                        mAdapter.notifyDataSetChanged();
                        Log.d(TAG, "-根据条码查询数据mDataList--what ");
                    }

                    break;
                case 1:
                    mProgressDialog.dismiss();
                    ui_Updata("", "", "清空数据", "");
                    Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    break;
            }
        }
    };
    //  private InventorysScanningAdapter mAdapter;
    private DBManager mManager;
    private ProgressDialog mProgressDialog;
    public RecyclerAdapter mAdapter;
    private EditText mEd_qty;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = View.inflate(mContext, R.layout.fragment_inventory_scanning, null);
        }
        ButterKnife.bind(this, mView);
        CWSoundPoolUtil.initSoundPool(mContext);
        manager = new Barcode1DManager();
        if (manager == null) {
            Toast.makeText(mContext, "扫描初始化失败", Toast.LENGTH_SHORT).show();
        }
        manager.Open(mHandler);
        Util.initSoundPool(mContext);
        UtilNbu.initSoundPool(mContext);
        mManager = new DBManager(mContext);
        mManager.copyDBFile();
        initView();
        return mView;
    }


    @Override
    public void onStart() {
        super.onStart();

    }


    private void initView() { //初始化适配器数据  998852223837050260
        mRecyclerViewM.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        //适配器设置
        mRecyclerViewM.setAdapter(mAdapter = new RecyclerAdapter<InventorySub>(mContext, mDataList, R.layout.recycler_itme) {
            @Override
            public void convert(RecycleHolder holder, InventorySub data, int position) {
                holder.setText(R.id.name_1, data.getLocation());
                holder.setText(R.id.name_2, data.getCode());
                holder.setText(R.id.name_3, data.getBarode());
                holder.setText(R.id.qty1_num, data.getMoreThan() + "");
                holder.setText(R.id.qty2_num, data.getLessThan() + "");
                holder.setText(R.id.qty3_num, data.getDiscNumber() + "");
                holder.setText(R.id.qty4_num, data.getSjnumber() + "");


            }
        });

        //适配器设置点击事件
        mAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
            @Override
            public void OnItemClickListener(View view, int position) {
                InventorySub inventorySub = mDataList.get(position);
                pop(inventorySub);

            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private boolean isTrueQty = false;

    /**
     * 判断数量是否大于
     */
    private void get_qty() {

        if (mDataList != null && mDataList.size() > 0) {
            boolean isTrue = false;
            for (int i = 0; i < mDataList.size(); i++) {
                int siNumber = Integer.parseInt(mDataList.get(i).getSjnumber());//实际数
                int discNumber = mDataList.get(i).getDiscNumber();  //盘点数
                if (siNumber == 0 && discNumber == 0) {
                } else {
                    if (discNumber >= siNumber) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        CWSoundPoolUtil.play(1, 0);
                                        Timer timer = new Timer();
                                        timer.schedule(new TimerTask() {
                                            @Override
                                            public void run() {
                                            }
                                        }, 50);
                                        isTrueQty = true;
                                        validation_dialog();
                                    }

                                });
                            }
                        }).start();
                        isTrue = true;
                        break;
                    }
                }
            }
            if (!isTrue) {
                getBarcode();
            }
        } else {
            getBarcode();
        }

    }

    private void set_dismissColse() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mProgressDialog.dismiss();
            }
        });
    }


    private void getBarcode() {
        if (mButtSaninng.getText().toString().equals("扫描")) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    manager.Scan();
                }
            }).start();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.butt_saninng, R.id.but_chongsao, R.id.but_submit, R.id.rr_lmg, R.id.butt_eliminate})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.butt_saninng:

                getBarcode();
               /* if (booleanScainng) {
                    booleanScainng = false;
                    getBarcode();
                } else {
                    get_qty();
                }*/
                break;
            case R.id.but_chongsao:
                set_showDialog();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < mDataList.size(); i++) {
                            int sj = Integer.parseInt(mDataList.get(i).getSjnumber());
                            mManager.setupdateQtyNull(mDataList.get(i).getBarode(), mDataList.get(i).getCode(), sj);
                        }
                        set_dismissColse();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ui_Updata("", "", "清空数据", "");
                            }
                        });
                    }
                }).start();


                Toast.makeText(mContext, "清空数据成功", Toast.LENGTH_SHORT).show();
                break;

            case R.id.but_submit:  //提交
                String qty = mSaoSjQty.getText().toString();
                if (qty.equals("0")) {
                    Toast.makeText(mContext, "请扫描条码", Toast.LENGTH_SHORT).show();
                } else {
                    dialog();
                }

            case R.id.rr_lmg: //刷新数据
                if (mLocation.getText().toString().equals("")) {
                    set_Toast("暂无数据");
                    ui_Updata("", "", "清空数据", "");
                } else {
                    ui_Updata(mLocation.getText().toString(), "", "货位信息", "");
                }
                break;
            case R.id.butt_eliminate:
                ui_Updata("", "", "清空数据", "");
                break;
        }
    }

    /**
     * 弹出对话框提示是否确定要重扫
     */
    private void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("提交任务吗？");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                set_showDialog();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<InventorySub> stateSubDataList = mManager.findStateSubDataList("已盘"); //查询出状态为已盘 数据
                        if (stateSubDataList != null && stateSubDataList.size() > 0) {
                            mManager.insertTsakSubData(stateSubDataList); //提交已盘数据
                            //修改状态
                            for (int i = 0; i < stateSubDataList.size(); i++) {
                                String barode = stateSubDataList.get(i).getBarode();
                                mManager.updateState(barode, "已提交");
                            }
                            set_dismissColse();
                            mHandler.sendEmptyMessage(1);
                        } else {
                            set_dismissColse();
                            set_Toast("暂无扫描数据");
                        }
                    }
                }).start();

                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void set_showDialog() {
        mProgressDialog = ProgressDialog.show(mContext, "", "正在提交数据请稍等");
        mProgressDialog.setCancelable(false);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.show();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int keyCode = intent.getIntExtra("keyCode", 0);
        Log.d(TAG, "按了按键，keycode是=" + intent.getIntExtra("keyCode", 0));
        switch (keyCode) {
            case 133:
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mButtSaninng.isEnabled()) {
                            mButtSaninng.performClick();
                        }
                    }
                });
                break;
        }
    }


    /*****
     * 验证条码
     */
    public void barcode_Validation(String strBarcode) {
        ButterKnife.bind(this, mView);
        //  set_showDialog();
        String locationTv = mLocation.getText().toString();
        //  第一次扫描 ：扫描条码 识别是否是货位
        if (locationTv.equals("")) {
            if (strBarcode.length() < 10) {
                //     1. 是货位  查询出 货位对应 款号显示  ，所有存入集合List 显示
                ui_Updata(strBarcode, "", "货位信息", "");
            } else {
                //  2. 不是货位是条码：按照条码 查出货位 ，在查出对应 款式显示，所有存入集合List。
                InventorySub barodeSub = mManager.findBarodeSub(strBarcode);
                if (barodeSub != null) {
                    String locationSub = barodeSub.getLocation();
                    if (locationSub == null) {
                        set_Toast("暂无查到改条码货位信息");
                    } else {
                        ui_Updata(locationSub, strBarcode, "第一次扫描", "");
                    }
                } else {
                    set_Toast("暂无查到改条码货位信息");

                    // 条码 没找到 货位  根据 条码查出  对应 款式
                    //如果 查询到对应款式
                    //弹出 框 填写 库位
                    //


                }


            }
        } else {

            //    第2次扫描：扫描条码
            if (strBarcode.length() < 10) {    //判断第2次扫描是否 扫描到 货位 还是条码
                //   1如果为货位是否与显示货位相同
                if (locationTv.equals(strBarcode)) {
                    if (mDataList == null && mDataList.size() < 0) {
                        //更新UI
                        ui_Updata(strBarcode, "", "货位信息", "");
                    }
                } else {
                    //   不相同更换货位显示，查询款式存入集合list显示
                    //更新UI
                    ui_Updata(strBarcode, "", "货位信息", "");
                }

            } else {
                //    2 如果 为条码
                //    在 list集合对应条码数量增加
                //    2 如果集合没对应条码 查询改条码 对应 货位 提示用户。
                if (mDataList == null && mDataList.size() < 0) {
                    ui_Updata(locationTv, strBarcode, "货位信息", "");
                }
                if (mDataList != null && mDataList.size() > 0) {
                    ui_Updata("", strBarcode, "第二次扫描", "");
                }
            }
        }

    }
    private void ui_Updata(String locationStr, final String barodeStr, String str, String delete) {
        int qty = 0;
        int discQty = 0;
        int moreQty = 0;
        int lessQty = 0;
        if (str.equals("清空数据")) {
            mButChongsao.setEnabled(false);
            mButSubmit.setEnabled(false);
            mSaoSjQty.setText(("0"));
            mDiscNumber.setText(("0"));
            mAddQty3.setText("0");
            mAddQty4.setText("0");
            mLocation.setText("");
            mDataList.clear();
            mAdapter.setDatas(mDataList);
            mAdapter.notifyDataSetChanged();
            return;
        } else if (str.equals("货位信息")) {
            mButSubmit.setEnabled(true);
            mButChongsao.setEnabled(true);
            mLocation.setText(locationStr);
            mDataList.clear();
            mDataList = mManager.findLocationSubListData(locationStr);
            if (mDataList != null && mDataList.size() > 0) {
                for (int i = 0; i < mDataList.size(); i++) {
                    int sj = Integer.parseInt(mDataList.get(i).getSjnumber());
                    qty = qty + sj;
                    int discNumber = mDataList.get(i).getDiscNumber();
                    discQty = discQty + discNumber;
                    Log.d(TAG, "-根据条码查询数据  货位信息mDataList-- " + i);
                    int mtq = mDataList.get(i).getMoreThan();
                    moreQty = moreQty + mtq;
                    int ltq = mDataList.get(i).getLessThan();
                    lessQty = lessQty + ltq;
                }
                mAddQty3.setText(moreQty + "");
                mAddQty4.setText(lessQty + "");
                mSaoSjQty.setText((qty + ""));
                mDiscNumber.setText((discQty + ""));
            } else {
                //提示 用户 没找到对应 货位信息
                set_Toast("----暂无找到该货位信息");
                mLocation.setText("");
                mSaoSjQty.setText(("0"));
                mDiscNumber.setText(("0"));
            }

            //----------删除
            if (delete.equals("删除")) {
                for (int i = 0; i < mDataList.size(); i++) {
                    String barode = mDataList.get(i).getBarode();
                    if (barode.equals(barodeStr)) {
                        InventorySub inventorySub = mDataList.get(i);
                        mDataList.remove(i);
                        mDataList.add(0, inventorySub);
                        break;
                    }
                }
            }


            mAdapter.setDatas(mDataList);

            mAdapter.notifyDataSetChanged();
            return;
        } else if (str.equals("第一次扫描")) {
            mLocation.setText(locationStr);
            mButSubmit.setEnabled(true);
            mButChongsao.setEnabled(true);
            //根据 货位查询出 所有条码
            mDataList = mManager.findLocationSubListData(locationStr);
            if (mDataList != null && mDataList.size() > 0) {
                for (int i = 0; i < mDataList.size(); i++) {
                    int sj = Integer.parseInt(mDataList.get(i).getSjnumber());
                    qty = qty + sj;
                    int discNumber = mDataList.get(i).getDiscNumber();
                    discQty = discQty + discNumber;
                    Log.d(TAG, "-根据条码查询数据mDataList-- " + i);
                    int mtq = mDataList.get(i).getMoreThan();
                    moreQty = moreQty + mtq;
                    int ltq = mDataList.get(i).getLessThan();
                    lessQty = lessQty + ltq;

                }
                mAddQty3.setText(moreQty + "");
                mAddQty4.setText(lessQty + "");
                mSaoSjQty.setText((qty + ""));
                mDiscNumber.setText((discQty + ""));
                mAdapter.setDatas(mDataList);
                mButSubmit.setEnabled(true);
                mButChongsao.setEnabled(true);
                mAdapter.notifyDataSetChanged();
                Log.d(TAG, "-根据条码查询数据mDataList--qty " + qty);


                boolean isTrueQty = false;
                for (int i = 0; i < mDataList.size(); i++) { //在扫描当前库位 查找条码
                    String barode = mDataList.get(i).getBarode();
                    int sjNum = Integer.parseInt(mDataList.get(i).getSjnumber());
                    int discNum = mDataList.get(i).getDiscNumber();
                    if (discNum >= sjNum && barode.equals(barodeStr)) { //判断是否盘点数量等于 实际数量 并且 条码和 扫描条码一样
                        isTrueQty = true;
                        break;
                    } else {
                        if (barode.equals(barodeStr)) {
                            mDataList.get(i).setDiscNumber(mDataList.get(i).getDiscNumber() + 1);
                            final int disc = Integer.parseInt(mDiscNumber.getText().toString());
                            mManager.updateQtyData(barode, "已盘");
                            mDiscNumber.setText((disc + 1) + "");
                            int sj = Integer.parseInt(mDataList.get(i).getSjnumber()); //数据数
                            int discNumber = mDataList.get(i).getDiscNumber();//盘点数
                            if (discNumber > sj) {
                                mDataList.get(i).setMoreThan(mDataList.get(i).getMoreThan() + 1);
                                int qty3 = Integer.parseInt(mAddQty3.getText().toString());
                                mAddQty3.setText((qty3 + 1) + "");
                                mManager.updateQtyjia(mDataList.get(i).getBarode(), "moreThan");
                            } else {
                                int lessThan = mDataList.get(i).getLessThan();
                                if (lessThan > 0) {
                                    mDataList.get(i).setLessThan(mDataList.get(i).getLessThan() - 1);
                                    int qty4 = Integer.parseInt(mAddQty4.getText().toString());
                                    mAddQty4.setText((qty4 - 1) + "");
                                    mManager.updateQtyJin(mDataList.get(i).getBarode(), "lessThan");
                                }
                            }
                            //移出
                            InventorySub inventorySub = mDataList.get(i);
                            mDataList.remove(i);
                            mDataList.add(0, inventorySub);


                            mAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }

                if (isTrueQty) {
                    CWSoundPoolUtil.play(1, 0);
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                        }
                    }, 50);
                    mButtSaninng.setEnabled(false);
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("提示");
                    builder.setMessage("数量过多条码为：" + barodeStr);
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            mButtSaninng.setEnabled(true);
                            for (int i = 0; i < mDataList.size(); i++) { //在扫描当前库位 查找条码
                                String barode = mDataList.get(i).getBarode();
                                if (barode.equals(barodeStr)) {
                                    mDataList.get(i).setDiscNumber(mDataList.get(i).getDiscNumber() + 1);
                                    final int disc = Integer.parseInt(mDiscNumber.getText().toString());
                                    mManager.updateQtyData(barode, "已盘");
                                    mDiscNumber.setText((disc + 1) + "");
                                    int sj = Integer.parseInt(mDataList.get(i).getSjnumber()); //数据数
                                    int discNumber = mDataList.get(i).getDiscNumber();//盘点数
                                    if (discNumber > sj) {
                                        mDataList.get(i).setMoreThan(mDataList.get(i).getMoreThan() + 1);
                                        int qty3 = Integer.parseInt(mAddQty3.getText().toString());
                                        mAddQty3.setText((qty3 + 1) + "");
                                        mManager.updateQtyjia(mDataList.get(i).getBarode(), "moreThan");
                                    } else {
                                        int lessThan = mDataList.get(i).getLessThan();
                                        if (lessThan > 0) {
                                            mDataList.get(i).setLessThan(mDataList.get(i).getLessThan() - 1);
                                            int qty4 = Integer.parseInt(mAddQty4.getText().toString());
                                            mAddQty4.setText((qty4 - 1) + "");
                                            mManager.updateQtyJin(mDataList.get(i).getBarode(), "lessThan");
                                        }
                                    }
                                    //移出 排序
                                    InventorySub inventorySub = mDataList.get(i);
                                    mDataList.remove(i);
                                    mDataList.add(0, inventorySub);


                                    mAdapter.notifyDataSetChanged();
                                    break;
                                }
                            }
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            mButtSaninng.setEnabled(true);
                        }
                    });
                    builder.create().show();
                }
            }

            return;
        } else if (str.equals("第二次扫描")) {
            mButSubmit.setEnabled(true);
            mButChongsao.setEnabled(true);
            boolean isTrueQty = false;
            for (int i = 0; i < mDataList.size(); i++) { //在扫描当前库位 查找条码 有就更新数据
                String barode = mDataList.get(i).getBarode();
                int sjNum = Integer.parseInt(mDataList.get(i).getSjnumber());
                int discNum = mDataList.get(i).getDiscNumber();
                if (discNum >= sjNum && barode.equals(barodeStr)) {
                    isTrueQty = true;
                    break;
                } else {
                    if (barode.equals(barodeStr)) {
                        mDataList.get(i).setDiscNumber(mDataList.get(i).getDiscNumber() + 1);
                        final int disc = Integer.parseInt(mDiscNumber.getText().toString());
                        mManager.updateQtyData(barode, "已盘");
                        mDiscNumber.setText((disc + 1) + "");
                        int sj = Integer.parseInt(mDataList.get(i).getSjnumber()); //数据数
                        int discNumber = mDataList.get(i).getDiscNumber();//盘点数
                        if (discNumber > sj) {
                            mDataList.get(i).setMoreThan(mDataList.get(i).getMoreThan() + 1);
                            int qty3 = Integer.parseInt(mAddQty3.getText().toString());
                            mAddQty3.setText((qty3 + 1) + "");
                            mManager.updateQtyjia(mDataList.get(i).getBarode(), "moreThan");
                        } else {
                            int lessThan = mDataList.get(i).getLessThan();
                            if (lessThan > 0) {
                                mDataList.get(i).setLessThan(mDataList.get(i).getLessThan() - 1);
                                int qty4 = Integer.parseInt(mAddQty4.getText().toString());
                                mAddQty4.setText((qty4 - 1) + "");
                                mManager.updateQtyJin(mDataList.get(i).getBarode(), "lessThan");
                            }

                        }

                        //移出 排序
                        InventorySub inventorySub = mDataList.get(i);
                        mDataList.remove(i);
                        mDataList.add(0, inventorySub);

                        mAdapter.setDatas(mDataList);
                        mAdapter.notifyDataSetChanged();
                        return;
                    }
                }
            }


            if (isTrueQty) {
                CWSoundPoolUtil.play(1, 0);
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                    }
                }, 50);
                mButtSaninng.setEnabled(false);
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("提示");
                builder.setMessage("数量过多条码为：" + barodeStr);
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mButtSaninng.setEnabled(true);
                        for (int i = 0; i < mDataList.size(); i++) { //在扫描当前库位 查找条码
                            String barode = mDataList.get(i).getBarode();
                            if (barode.equals(barodeStr)) {
                                mDataList.get(i).setDiscNumber(mDataList.get(i).getDiscNumber() + 1);
                                final int disc = Integer.parseInt(mDiscNumber.getText().toString());
                                mManager.updateQtyData(barode, "已盘");
                                mDiscNumber.setText((disc + 1) + "");
                                int sj = Integer.parseInt(mDataList.get(i).getSjnumber()); //数据数
                                int discNumber = mDataList.get(i).getDiscNumber();//盘点数
                                if (discNumber > sj) {
                                    mDataList.get(i).setMoreThan(mDataList.get(i).getMoreThan() + 1);
                                    int qty3 = Integer.parseInt(mAddQty3.getText().toString());
                                    mAddQty3.setText((qty3 + 1) + "");
                                    mManager.updateQtyjia(mDataList.get(i).getBarode(), "moreThan");
                                } else {
                                    int lessThan = mDataList.get(i).getLessThan();
                                    if (lessThan > 0) {
                                        mDataList.get(i).setLessThan(mDataList.get(i).getLessThan() - 1);
                                        int qty4 = Integer.parseInt(mAddQty4.getText().toString());
                                        mAddQty4.setText((qty4 - 1) + "");
                                        mManager.updateQtyJin(mDataList.get(i).getBarode(), "lessThan");
                                    }
                                }

                                //移出 排序
                                InventorySub inventorySub = mDataList.get(i);
                                mDataList.remove(i);
                                mDataList.add(0, inventorySub);

                                mAdapter.notifyDataSetChanged();
                                break;
                            }
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mButtSaninng.setEnabled(true);
                    }
                });
                builder.create().show();
            }


            // 如果不在 当前货位 去所有货位查询
            InventorySub barodeSub = mManager.findBarodeSub(barodeStr);
            if (barodeSub == null) {
                set_Toast("款式没对应货位");
                return;
            }
            String location = barodeSub.getLocation();
            if (mLocation.getText().toString().equals(location)) {

            } else {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CWSoundPoolUtil.play(1, 0);
                                Timer timer = new Timer();
                                timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                    }
                                }, 50);

                            }

                        });
                    }
                }).start();


                //播放提示音
                if (location == null || location.equals("")) {
                    location = "不存在";
                }
                String strDialog = "款式货位号：" + location + "     非本货位款式，请处理！ ";
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("提示");
                builder.setMessage(strDialog);
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mButtSaninng.setEnabled(true);
                        dialog.dismiss();
                    }
                }).create();

                builder.setCancelable(false);
                builder.show();

            }
        }
    }

    public void set_Toast(final String m_Toast) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "" + m_Toast, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 弹出对话框提示是否确定要重扫
     */
    private void validation_dialog() {
        mButtSaninng.setEnabled(false);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage("数量过多");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mButtSaninng.setEnabled(true);

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mButtSaninng.setEnabled(true);
            }
        });
        builder.create().show();
    }
    private boolean popBoolean=true;
    /**
     * 弹出框
     **/
    private void pop(final InventorySub inventorySub) {


        if (popBoolean) {
            popBoolean = false;
            //创建布局
            LayoutInflater layoutInflater = LayoutInflater.from(mContext);
            View view = layoutInflater.inflate(R.layout.popup_power, null);
            final PopupWindow mPopupWindow = new PopupWindow(view, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setAnimationStyle(R.style.popup_window);
            mPopupWindow.setContentView(view);

            ImageView lmage = (ImageView) view.findViewById(R.id.lmg_xxxx);
            TextView tv1 = (TextView) view.findViewById(R.id.pop_tv1);
            TextView tv2 = (TextView) view.findViewById(R.id.pop_tv2);
            TextView tv3 = (TextView) view.findViewById(R.id.pop_tv3);
            TextView qty1_num = (TextView) view.findViewById(R.id.qty1_num);
            TextView qty2_num = (TextView) view.findViewById(R.id.qty2_num);
            TextView qty3_num = (TextView) view.findViewById(R.id.qty3_num);
            TextView qty4_num = (TextView) view.findViewById(R.id.qty4_num);
            mEd_qty = (EditText) view.findViewById(R.id.ed_chongsao);
            ;
            Button but1 = (Button) view.findViewById(R.id.button1);
            Button but2 = (Button) view.findViewById(R.id.button2);

            tv1.setText(inventorySub.getLocation().toString());
            tv2.setText(inventorySub.getCode().toString());
            tv3.setText(inventorySub.getBarode());
            qty1_num.setText(inventorySub.getMoreThan() + "");
            qty2_num.setText(inventorySub.getLessThan() + "");
            qty3_num.setText(inventorySub.getDiscNumber() + "");
            qty4_num.setText(inventorySub.getSjnumber() + "");


            lmage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    popBoolean = true;
                }
            });

            but1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    popBoolean = true;
                }
            });

            but2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    set_showDialog();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            int sj = Integer.parseInt(inventorySub.getSjnumber().toString()); //实际数量
                            int edQty = Integer.parseInt(mEd_qty.getText().toString());     //重扫数量
                            int discQty = inventorySub.getDiscNumber(); //盘点数量
                            int lessThan = inventorySub.getLessThan(); //异差数量
                            int moreThan = inventorySub.getMoreThan();//多于数量
                            if (edQty > discQty) {
                                set_Toast("重扫数量过多");
                            } else {
                                if (discQty > sj) {
                                    if (edQty > moreThan) { //重扫数量 大于 大于数量
                                        mManager.setupdateQty(inventorySub.getBarode(), inventorySub.getCode(), 0, ((edQty - moreThan) + lessThan), (discQty - edQty)); //删除数据
                                    } else {//重扫数量 小于
                                        mManager.setupdateQty(inventorySub.getBarode(), inventorySub.getCode(), (moreThan - edQty), (lessThan), (discQty - edQty)); //删除数据
                                    }

                                } else {
                                    //如果盘点 等于或者小于 实际数，盘点数量 减去 重扫数量  ,并且在在异差数量 加 重扫数量
                                    // int moreThan, int lessThan, int discNumber
                                    mManager.setupdateQty(inventorySub.getBarode(), inventorySub.getCode(), 0, (lessThan + edQty), (discQty - edQty)); //删除数据
                                }
                            }

                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mLocation.getText().toString().equals("")) {
                                        set_Toast("暂无数据");
                                        ui_Updata("", "", "清空数据", "");
                                    } else {
                                        ui_Updata(mLocation.getText().toString(), inventorySub.getBarode(), "货位信息", "删除");


                                        mPopupWindow.dismiss();
                                        popBoolean = true;
                                    }
                                }
                            });
                            set_dismissColse();
                        }
                    }).start();
                }
            });
            /***
             * 点击按钮 数量-1 ，
             * 判断 已盘数量 是否 对于 事件数量  如果大于就 在 多于  -1，并且 已盘数量 -1
             *                                       否则 在 异差 数量 + 1 ，
             *
             */
            WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();//创建当前界面的一个参数对象
            params.alpha = 0.8f;
            getActivity().getWindow().setAttributes(params);//把该参数对象设置进当前界面中
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
                    params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                    getActivity().getWindow().setAttributes(params);
                }
            });
            //第一个参数为父View对象，即PopupWindow所在的父控件对象，第二个参数为它的重心，后面两个分别为x轴和y轴的偏移量
            mPopupWindow.showAtLocation(layoutInflater.inflate(R.layout.activity_main, null), Gravity.CENTER, 0, 0);
        }
    }
}
